# coding=utf-8
import base64
from datetime import date, datetime

import akshare as ak
import baostock as bs
import requests

username = 'script'
password = '123456a.'


def trans_date(date_str) -> date:
    return datetime.strptime(date_str, '%Y-%m-%d').date()


# bct服务
# bct_url = "http://10.1.6.61"
bct_url = "http://10.1.6.177"
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36 Edg/97.0.1072.69 '
today = str(date.today())
start_date_str = '2023-01-01'
start_date = datetime.strptime(start_date_str, '%Y-%m-%d').date()
#start_date = date.today()
end_date = date.today()

# 指数
index_instruments = [
    # {'exchange': 'sh', 'instrumentId': '000016'},
    # {'exchange': 'sh', 'instrumentId': '000852'},
    # {'exchange': 'sh', 'instrumentId': '000300'},
    # {'exchange': 'sh', 'instrumentId': '000905'},
    {'exchange': 'sh', 'instrumentId': '000902'}
]
# 个股 000887.SZ
stock_instruments = [
    # {'exchange': 'sz', 'instrumentId': '000651'},
    {'exchange': 'sz', 'instrumentId': '000887'}
]

instruments = [
    {'exchange': 'dce', 'instrumentId': 'JM2405'}
]

# etf
instruments_etf = [
    # {'exchange': 'sh', 'instrumentId': '510050'},
    # {'exchange': 'sh', 'instrumentId': '510500'},
    {'exchange': 'sz', 'instrumentId': '159845'}

]

# 商品
instruments_commodity = [
    {'exchange': 'DCE', 'instrumentId': 'AU9999'}
]
start_date_commodity = '20240101'
end_date_commodity = '20240201'

# 金交所
instruments_sge = [
    {'exchange': 'SGE', 'instrumentId': 'AU9999'}
]


def saveBct(token, data_list):
    for data in data_list:
        headers = {"Authorization": "Bearer " + token}
        json = {"instance": "close", "instrumentId": data[2], "valuationDate": data[0], "quote": {"close": data[1]}}
        # 获得json 数据
        r = requests.post(url=bct_url + '/bct/market-data-service/quote/save', json=json, headers=headers)
        print(r.json())


def saveQ():
    lg = bs.login()
    # 参数设置
    token = _get_token(username, password, bct_url)
    for instrument in instruments:

        print(today)
        rs = bs.query_history_k_data_plus(instrument.get("exchange") + "." + instrument.get("instrumentId"),
                                          "date,close",
                                          start_date=start_date, end_date=end_date,
                                          frequency="d", adjustflag="3")
        data_list = []
        while (rs.error_code == '0') & rs.next():
            # 获取一条记录，将记录合并在一起
            quote_data = rs.get_row_data()
            quote_data.append(instrument.get("instrumentId") + "." + instrument.get("exchange").upper())
            data_list.append(quote_data)
        saveBct(token, data_list)

    # 获得对应token


def save_stock():
    token = _get_token(username, password, bct_url)
    for instrument in stock_instruments:
        df = ak.stock_zh_a_hist(symbol=instrument.get("instrumentId"), period="daily",
                                start_date=str(start_date).replace("-", ""), end_date=str(end_date).replace("-", ""),
                                adjust="")
        data_list = []
        for index, row in df.iterrows():
            quote_data = []
            if row['日期'] >= start_date and row['日期'] <= end_date:
                quote_data.append(str(row['日期']))
                quote_data.append(row['收盘'])
                quote_data.append(instrument.get("instrumentId") + "." + instrument.get("exchange").upper())
                data_list.append(quote_data)
        saveBct(token, data_list)


def save_index():
    # 参数设置
    token = _get_token(username, password, bct_url)
    for instrument in index_instruments:
        df = ak.stock_zh_index_daily(symbol=instrument.get("exchange") + instrument.get("instrumentId"))
        data_list = []
        for index, row in df.iterrows():
            quote_data = []
            if row['date'] >= start_date and row['date'] <= end_date:
                quote_data.append(str(row['date']))
                quote_data.append(row['close'])
                quote_data.append(instrument.get("instrumentId") + "." + instrument.get("exchange").upper())
                data_list.append(quote_data)
        saveBct(token, data_list)


def save_etf_q():
    # 参数设置
    token = _get_token(username, password, bct_url)
    for instrument in instruments_etf:
        df = ak.fund_etf_hist_sina(symbol=instrument.get("exchange") + instrument.get("instrumentId"))
        data_list = []
        for index, row in df.iterrows():
            quote_data = []
            if row['date'] >= start_date and row['date'] <= end_date:
                quote_data.append(str(row['date']))
                quote_data.append(row['close'])
                quote_data.append(instrument.get("instrumentId") + "." + instrument.get("exchange").upper())
                data_list.append(quote_data)
        saveBct(token, data_list)


def save_commodity_q():
    # 参数设置
    token = _get_token(username, password, bct_url)
    for instrument in instruments_commodity:
        df = ak.futures_main_sina(symbol=instrument.get("instrumentId"), start_date=start_date_commodity,end_date=end_date_commodity)
        data_list = []
        for index, row in df.iterrows():
            list = []
            list.append(str(row['日期']))
            list.append(row['收盘价'])
            list.append(instrument.get("instrumentId") + "." + instrument.get("exchange").upper())
            data_list.append(list)

        saveBct(token, data_list)


def save_sge():
    # 参数设置
    token = _get_token(username, password, bct_url)
    for instrument in instruments_sge:
        instum = instrument.get("instrumentId")
        if instum == 'AU9999':
            instum = 'Au99.99'
        df = ak.spot_hist_sge(symbol=instum)
        data_list = []
        for index, row in df.iterrows():
            list = []
            if row['date'] >= start_date and row['date'] <= end_date:
                list.append(str(row['date']))
                list.append(row['close'])
                list.append(instrument.get("instrumentId") + "." + instrument.get("exchange").upper())
                data_list.append(list)

        saveBct(token, data_list)


def _get_token(auth_username: str, auth_password: str, server_url: str,
               base64_encode: bool = True) -> str:
    auth_url = "%s%s" % (server_url, '/api/auth-service/users/login')

    if base64_encode:
        usr_name = base64.b64encode(auth_username.encode())
        usr_pwd = base64.b64encode(auth_password.encode())
    else:
        usr_name = auth_username
        usr_pwd = auth_password

    auth_body = {
        'userName': usr_name.decode(),
        'password': usr_pwd.decode()
    }
    headers = {'User-Agent': user_agent}
    auth = requests.post(auth_url, json=auth_body, headers=headers)
    try:
        _token = auth.json()['token']
        return _token
    except Exception:
        error_message = auth.json()['errorMessage']
        raise ValueError(error_message)


# if __name__ == '__main__':
#     save_etf_q()
#
# if __name__ == '__main__':
#     saveQ()

if __name__ == '__main__':
    # save_sge()
    # print('/n')

    #save_index()
    print('/n')

    # save_stock()
    # print('/n')

    save_etf_q()
    # print('/n')
